﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using Microsoft.AspNet.SignalR.Client;

namespace AutoCryCJService
{
    public partial class Service1 : ServiceBase
    {
        public DateTime cjTime = DateTime.Now;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            Thread thread1 = new Thread(() =>
            {
                RcyCheckService();
            });
            thread1.Start();
        }

        /// <summary>
        /// 循环检测数据服务
        /// </summary>
        private void RcyCheckService()
        {
            while(true)
            {
                try
                {
                    string serviceName = "H6采集服务";
                    ServiceController curServiceController = null;
                    ServiceController[] services = ServiceController.GetServices();
                    foreach (ServiceController sc in services)
                    {
                        if (sc.ServiceName.ToLower() == serviceName.ToLower())
                        {
                            curServiceController = sc;
                        }
                    }
                    if (curServiceController != null)
                    {
                        ////优先判断采集通讯是否中断
                        //if (cjTime.AddMinutes(3) < DateTime.Now)
                        //{
                        //    //普通方式，停止服务(正常停止不使用了)
                        //    //curServiceController.Stop();
                        //    // 获取服务的PID
                        //    int pid = GetServiceProcessId(curServiceController.ServiceName);
                        //    if (pid != 0)
                        //    {
                        //        try
                        //        {
                        //            Process process = Process.GetProcessById(pid);
                        //            process.Kill();
                        //        }
                        //        catch (ArgumentException)
                        //        {
                        //        }
                        //        catch (Exception ex)
                        //        {
                        //        }
                        //    }
                        //    Thread.Sleep(1000 * 30);
                        //}
                        if (curServiceController.Status == ServiceControllerStatus.Stopped)
                        {
                            //需要重启服务
                            curServiceController.Start();
                            Thread.Sleep(5000);
                            RunSignalR();
                        }
                    }
                }
                catch (Exception ex)
                {
                }
                Thread.Sleep(5000);
            }
        }


        private string ReadDeviceConfig()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"\DeviceConfigData.ini";
            return File.ReadAllText(path);
            //try
            //{
            //    SQLiteHelper sqlLiteHelper = new SQLiteHelper("CJ.db");
            //    System.Data.DataTable lastRecordDt = sqlLiteHelper.ExecuteDataTable("select * from LastRecord");
            //    if (lastRecordDt != null && lastRecordDt.Rows.Count > 0)
            //    {
            //        Log.SaveNote(lastRecordDt.Rows[0]["record"].ToString());
            //        return lastRecordDt.Rows[0]["record"].ToString();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    return "";
            //}
            //return "";
        }

        private void RunSignalR()
        {
            //10008作为本地signalR通讯端口
            var connection = new HubConnection("http://127.0.0.1:10008/signalr");
            var dataCollectHub = connection.CreateHubProxy("DataCollectHub");
            //开始连接
            connection.Start().ContinueWith(t =>
            {
                if (!t.IsFaulted)
                {
                    string[] content = ReadDeviceConfig().Split('^');
                    dataCollectHub.Invoke("InitDeviceCollectConfig", content[0], content[1], content[2]);
                    Thread.Sleep(5000);
                    dataCollectHub.Invoke("PlayAllDeviceCollect");
                }
                else
                {
                }
            });


            dataCollectHub.On("OnGetAllDeviceStatus", (string listDeviceConfigStr) =>
            {
                //如果有回调，更新下日期状态
                cjTime = DateTime.Now;
            });

        }


        private int GetServiceProcessId(string serviceName)
        {
            try
            {
                // 执行sc queryex命令获取服务信息
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "sc",
                    Arguments = $"queryex {serviceName}",
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardOutput = true
                };

                using (Process process = new Process { StartInfo = startInfo })
                {
                    process.Start();
                    string output = process.StandardOutput.ReadToEnd();
                    process.WaitForExit();

                    // 解析输出以获取PID
                    string[] lines = output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string line in lines)
                    {
                        if (line.Contains("PID"))
                        {
                            int startIndex = line.IndexOf(":") + 1;
                            string pidStr = line.Substring(startIndex).Trim();
                            if (int.TryParse(pidStr, out int pid))
                            {
                                return pid;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取服务进程ID时出错: {ex.Message}");
            }

            return 0;
        }




        protected override void OnStop()
        {
        }
    }
}
